package com.rentong.basic;

import com.github.pagehelper.PageInfo;
import com.rentong.json.JsonUtils;

import javax.persistence.Transient;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ZXY
 * @ClassName: DataGrid
 * @Description: 返回给前端分页数据
 * @date 2017/10/18 20:19
 */
public class DataGrid<T> {

    //每页的内容
    @Transient
    private List<T> rows;

    //总记录数
    @Transient
    private Integer total;

    public List<T> getRows() {
        return rows;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    public static <T> DataGrid<T> pageData(List<T> list) {
        if (list != null && list.size() > 0) {
            PageInfo<T> pageInfo = new PageInfo<>(list);
            DataGrid dataGrid = new DataGrid();
            dataGrid.setTotal((int) pageInfo.getTotal());
            dataGrid.setRows(list);
            return dataGrid;
        }
        return noData();
    }

    //查无数据返回
    public static <T> DataGrid<T> noData() {
        DataGrid dataGrid = new DataGrid();
        dataGrid.setTotal(0);
        dataGrid.setRows(new ArrayList());
        return dataGrid;
    }

    /**
     * json 序列化输出
     *
     * @param grid
     * @param response
     */
    public static void writeJson(Object grid, HttpServletResponse response) {
        try {
            String json = JsonUtils.translateToJson(grid);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(json);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
